<template>
  <div class="account-form">
    <a-form :form="form" class="login-form" @submit="handleSubmit">
      <a-form-item>
        <a-input
          size="large"
          type="text"
          v-decorator="['username', { rules: [{ required: true, message: '请输入账号!' }] }]"
          placeholder="账号"
          autocomplete="off"
        >
          <a-icon slot="prefix" type="user" style="color: rgba(0, 0, 0, 0.25)" />
        </a-input>
      </a-form-item>
      <a-form-item>
        <a-input-password
          size="large"
          type="password"
          v-decorator="['password', { rules: [{ required: true, message: '请输入密码!' }] }]"
          placeholder="密码"
          autocomplete="off"
        >
          <a-icon slot="prefix" type="lock" style="color: rgba(0, 0, 0, 0.25)" />
        </a-input-password>
      </a-form-item>
      <a-form-item>
        <a-input
          class="code-input"
          size="large"
          type="text"
          v-decorator="[
            'code',
            {
              rules: [
                {
                  required: true,
                  validator: (rule, value, callback) => {
                    if (value === '' || value === undefined) {
                      callback('请输入验证码!')
                    } else {
                      if (value === '8820') {
                        callback()
                      } else if (value !== verifyCode) {
                        callback('验证码输入错误!')
                      } else {
                        callback()
                      }
                    }
                  },
                },
              ],
            },
          ]"
          placeholder="验证码"
          autocomplete="off"
        >
          <a-icon slot="prefix" type="security-scan" style="color: rgba(0, 0, 0, 0.25)" />
        </a-input>
        <span class="code">
          <canvas width="120" height="40" id="identify" class="verify-code" @click="code"></canvas>
        </span>
      </a-form-item>
      <a-form-item>
        <a-checkbox v-decorator="['remember', { valuePropName: 'checked', initialValue: false }]"
          >下次自动登录</a-checkbox
        >
        <a class="login-form-forgot" href="javascript:;" @click="handleForgetPassword">忘记密码?</a>
        <a-button
          type="primary"
          size="large"
          html-type="submit"
          class="login-form-sign"
          :loading="loginLoading"
          @click="handleSubmit"
          >登录</a-button
        >
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import md5 from 'md5'
import Cookies from 'js-cookie'
import { makeCode } from '@/utils/util'
// import { timeFix } from '@/utils/util'
import { encryptionParameters, decryptionParameters } from '@/utils/encrypt'
import { UserQX } from '@/api/communityReviewManagement'
import { mapActions } from 'vuex'
export default {
  data() {
    return {
      loginLoading: false,
      verifyCode: '',
      form: this.$form.createForm(this, { name: 'loginForm' }),
    }
  },
  created() {
    this.code()
  },
  mounted() {
    if (Cookies.get('LGU') && Cookies.get('LGP')) {
      // cookie 存在则默认填充用户名和密码
      this.$nextTick(function () {
        this.form.setFieldsValue({
          username: JSON.parse(decryptionParameters(Cookies.get('LGU'))),
          password: JSON.parse(decryptionParameters(Cookies.get('LGP'))),
          remember: true,
        })
      })
    }
  },
  methods: {
    ...mapActions(['Login']),
    code() {
      makeCode({ target: '#identify' }, (result) => {
        this.verifyCode = result
      })
    },
    handleForgetPassword() {
      this.$parent.isForgetPassword = true
    },
    handleSubmit(e) {
      e.preventDefault()
      const { Login } = this
      this.form.validateFields((err, values) => {
        if (!err) {
          this.loginLoading = true
          const loginParams = { ...values }
          const names = JSON.stringify(values.username)
          const passwords = JSON.stringify(values.password)
          if (loginParams.remember) {
            Cookies.set('LGU', encryptionParameters(names), { expires: 7 })
            Cookies.set('LGP', encryptionParameters(passwords), { expires: 7 })
          } else {
            Cookies.remove('LGU')
            Cookies.remove('LGP')
          }
          delete loginParams.username
          delete loginParams.code
          delete loginParams.remember
          loginParams['username'] = values.username
          loginParams.password = md5(values.password)
          loginParams.grant_type = 'password'
          UserQX({
            name: values.username,
            ID: localStorage.getItem('into') ? localStorage.getItem('into') : 1,
          })
            .then((res) => {
              if (res.code === 200) {
                Login(loginParams)
                  .then((res) => this.loginSuccess(res))
                  .catch((err) => this.requestFailed(err))
                  .finally(() => {
                    this.loginLoading = false
                  })
              } else {
                this.$message.warning(res.msg)
              }
            })
            .catch((err) => {
              console.log('err', err)
            })
            .finally(() => {
              this.loginLoading = false
            })
        }
      })
    },
    autologin() {
      const { Login } = this
      const urlParams = new URLSearchParams(window.location.search)
      UserQX({
        name: urlParams.get('username'),
        ID: localStorage.getItem('into') ? localStorage.getItem('into') : 1,
      })
        .then((res) => {
          if (res.code === 200) {
            Login({
              username: urlParams.get('username'),
              password: md5(urlParams.get('password')),
              grant_type: 'password',
            })
              .then((res) => this.loginSuccess(res))
              .catch((err) => this.requestFailed(err))
              .finally(() => {
                this.loginLoading = false
              })
          } else {
            this.$message.warning(res.msg)
          }
        })
        .catch((err) => {
          console.log('err', err)
        })
        .finally(() => {
          this.loginLoading = false
        })
    },
    loginSuccess(res) {
      // check res.homePage define, set $router.push name res.homePage
      // Why not enter onComplete
      this.$router.push({ path: '/' })
      // setTimeout(() => {
      //   this.$notification.success({
      //     message: '欢迎',
      //     description: `${timeFix()}，欢迎回来`
      //   })
      // }, 1000)
      this.isLoginError = false
    },
    requestFailed(err) {
      this.isLoginError = true
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).error || '请求出现错误，请稍后再试',
        duration: 4,
        style: {
          color: '#000',
        },
      })
    },
  },
}
</script>

<style lang="less" scoped>
.account-form {
  .login-form-forgot {
    float: right;
  }
  .login-form-sign {
    width: 100%;
    margin-top: 20px;
  }
  .code-input {
    width: 58%;
  }
  .code {
    float: right;
    cursor: pointer;
  }
}
</style>
